﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.XPath;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
using System.IO;
using System.Text;
using System.Web.UI.HtmlControls;

/// <summary>
/// BSUtility 的摘要说明
/// </summary>
public abstract class BSUtility
{
    public static string mainUrl = GetMainUrl();//主页地址
    public static string attrPath = GetAttrPath(); //附件地址
    /// <summary>
    /// 日志文件夹
    /// </summary>
    public static string logPath = GetLogPath(); //附件地址

	public BSUtility()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}

    private static string GetMainUrl()
    {
        return ReadXmlFile("ConstDb.dll", "mainUrl");
    }
    private static string GetAttrPath()
    {
        return ReadXmlFile("ConstDb.dll", "AttrPath");
    }
    private static string GetLogPath()
    {
        return ReadXmlFile("ConstDb.dll", "LogPath");
    }

    #region 读取XML节点值
    /// <summary>
    /// 读取XML文件
    /// </summary>
    /// <param name="xmlFileName"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string ReadXmlFile(string xmlFileName, string key)
    {
        string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + xmlFileName;
        string m_return_val = String.Empty;
        string m_XPath = "/configuration/Cms";
        XPathDocument doc1 = new XPathDocument(filename);
        XPathNavigator nav1 = doc1.CreateNavigator();
        XPathNodeIterator iter1 = nav1.Select(m_XPath);
        if (iter1.MoveNext())
        {
            m_return_val = iter1.Current.GetAttribute(key, ""); ;
            if (iter1.MoveNext())
            {
                throw new Exception("配置文件有问题");
            }
        }
        else
        {
            throw new Exception("配置文件有问题");
        }
        string ExStr = "\r\n\t ";
        return m_return_val.Trim(ExStr.ToCharArray());
    }
    #endregion

    #region 绑定下拉框
    /// <summary>
    /// 将枚举值绑定到下拉框控件
    /// </summary>
    /// <param name="cb"></param>
    /// <param name="type"></param>
    //public static void BindEnumDropDownList(DropDownList ddl, string type)
    //{
    //    string enumValueStr = null;
    //    r_EnumValue enumValue = new r_EnumValue();
    //    DataTable dt = enumValue.GetEnumValueByType(type);
    //    if (dt.Rows.Count > 0)
    //    {
    //        enumValueStr = dt.Rows[0]["EnumValue"].ToString();
    //    }
    //    if (enumValueStr != null)
    //    {
    //        if (enumValueStr.Length > 0)
    //        {
    //            string[] enumArray = enumValueStr.Trim().Split(',');
    //            for (int i = 0; i < enumArray.Length; i++)
    //            {
    //                ddl.Items.Add(enumArray[i].Trim());
    //            }
    //        }
    //    }
    //}
    /// <summary>
    /// 列表类型控件数据绑定
    /// </summary>
    public static void BindListControl(ListControl listControl, DataTable dt, string dataTextFiled, string dataValueFiled)
    {
        listControl.DataSource = dt;
        listControl.DataTextField = dataTextFiled;
        listControl.DataValueField = dataValueFiled;
        listControl.DataBind();
    }

    #endregion   

    public static void WindowAlert(Page page, string alertString)
    {
        page.ClientScript.RegisterStartupScript(page.GetType(), "MsgBox", "<script type='text/javascript'>alert('" + alertString + "');</script>");
    }

    public static void JavaScript(Page page, string javaScriptStr)
    {
        page.ClientScript.RegisterStartupScript(page.GetType(), "MsgBox", "<script type='text/javascript'>" + javaScriptStr + "</script>");
    }

    public static void WriteLog(string txt)
    {
        try
        {
            string path = logPath + @"\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path += DateTime.Now.ToString("yyyyMMdd") + ".txt";
            if (!File.Exists(path))
            {
                File.Create(path);
            }
            FileStream fs;
            StreamWriter sw;
            fs = new FileStream(path, FileMode.Append);
            sw = new StreamWriter(fs, Encoding.Default);
            sw.Write(DateTime.Now.ToString("HH:mm:ss") + " " + txt + "\r\n");
            sw.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            //WriteLog("程序发生异常（WriteLog）。详情：" + ex.Message);
        }

    }

    public static void ExportDataTableToExcel(DataTable dt, string excelFileName)
    {
        GridView gv = new GridView();
        gv.DataSource = dt;
        gv.DataBind();
        string style = @"<style> .text { mso-number-format:\@; } </script> ";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = false;
        HttpContext.Current.Response.Charset = "GB2312";
        excelFileName = HttpUtility.UrlEncode(excelFileName, Encoding.GetEncoding("UTF-8"));
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + excelFileName + ".xls");
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();
                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }
                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    PrepareControlForExport(row);
                    table.Rows.Add(row);
                }
                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }
                //  render the table into the htmlwriter
                table.RenderControl(htw);
                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(style); //添加样式
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }
    public static void ExportGridViewToExcel(GridView gv, string excelFileName)
    {
        string style = @"<style> .text { mso-number-format:\@; } </script> ";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = false;
        HttpContext.Current.Response.Charset = "GB2312";
        excelFileName = HttpUtility.UrlEncode(excelFileName, Encoding.GetEncoding("UTF-8"));
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + excelFileName + ".xls");
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();
                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }
                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    PrepareControlForExport(row);
                    table.Rows.Add(row);
                }
                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }
                //  render the table into the htmlwriter
                table.RenderControl(htw);
                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(style); //添加样式
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));

            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }
            else if (current is HtmlAnchor)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HtmlAnchor).InnerText));
            }
            if (current.HasControls())
            {
                PrepareControlForExport(current);
            }
        }
    }


}